package yz.cp.back.admin.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import yz.cp.back.common.base.BaseController;
import yz.cp.back.common.res.ApiResult;
import yz.cp.back.s.entity.SysDict;
import yz.cp.back.s.entity.SysDictData;
import yz.cp.back.s.service.ISysDictDataService;
import yz.cp.back.s.service.ISysDictService;


/**
 * 字典管理接口
 * @author xukk
 */
@Slf4j
@RestController
@RequestMapping("/web/dict")
public class DictController extends BaseController {

    @Autowired
    private ISysDictService dictService;

    @Autowired
    private ISysDictDataService dictDataService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 获取全部数据
     * @return
     */
    @RequestMapping(value = "/getAll",method = RequestMethod.GET)
    public ApiResult getAll(){

       return renderOk().add(dictService.list(new QueryWrapper<SysDict>().lambda().orderByAsc(SysDict::getSortOrder)));
    }

    /**
     * 添加
     * @param dict
     * @return
     */
    @RequestMapping(value = "/add",method = RequestMethod.POST)
    public ApiResult add(@ModelAttribute SysDict dict){

        if(dictService.getOne(new QueryWrapper<SysDict>().lambda().eq(SysDict::getType,dict.getType()))!=null){
            return renderError("字典类型Type已存在");
        }
        dictService.save(dict);
        return renderOk("添加成功");
    }

    /**
     * 编辑
     * @param dict
     * @return
     */
    @RequestMapping(value = "/edit",method = RequestMethod.POST)
    public ApiResult edit(@ModelAttribute SysDict dict){

        SysDict old = dictService.getById(dict.getId());
        // 若type修改判断唯一
        if(!old.getType().equals(dict.getType())&&dictService.getOne(new QueryWrapper<SysDict>().lambda().eq(SysDict::getType,dict.getType()))!=null){
            return renderError("字典类型Type已存在");
        }
        dictService.updateById(dict);
        return renderOk();
    }

    /**
     * 通过id删除
     * @param id
     * @return
     */
    @RequestMapping(value = "/delByIds/{id}",method = RequestMethod.DELETE)
    public ApiResult delAllByIds(@PathVariable String id){


        SysDict dict = dictService.getById(id);
        dictService.removeById(id);
        dictDataService.remove(new QueryWrapper<SysDictData>().lambda().eq(SysDictData::getDictId,id));
        redisTemplate.delete("dictData::"+dict.getType());
        return renderOk("删除成功");
    }

    /**
     * 搜索字典
     * @param key
     * @return
     */
    @RequestMapping(value = "/search",method = RequestMethod.GET)
    public ApiResult searchPermissionList(@RequestParam String key){
        return renderOk().add(dictService.list(new QueryWrapper<SysDict>().lambda().like(SysDict::getTitle,key).or().like(SysDict::getType,key)));

    }
}
